/**
  * @title:NetTaskManager.java
  * TODO包含类名列表
  * Copyright (C) Shenzhen Futuo Technology Co.Ltd.All right reserved.
  * @version：v1.0,2015-9-1
  */
package helen.core.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import helen.core.iinterface.NetRequestTask;


/**@name NetTaskManager
 * @description 提供异步网络请求的类
 * @author max
 * @date 2015-9-1
 */
public class NetTaskManager
{
	//context
	private Context context = null;
	private Handler mHandler = null;
	//handler 需要回复的message的识别码
	private int messageWhat = 0;
	//获取数据后写入数据缓存的cache标识
	private String dataTag = "";
	//请求用的task
	private NetRequestTask task;
	//请求用线程
	private Thread thread;
	public NetRequestTask getTask() {
		return task;
	}
	public void setTask(NetRequestTask task) {
		this.task = task;
	}
	public static final int START_REQUEST_SUCCESS = 0;
	public static final int REQUEST_OFFLINE = 1;
	public NetTaskManager(Context context , Handler mHandler, int messageWhat,String dataTag){
		this.context = context ;
		this.mHandler = mHandler;
		this.dataTag = dataTag;
		this.messageWhat = messageWhat;
	}
	public void cannel(){
		if(thread.isAlive()){
			try {
				thread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	//抛出线程进行网络请求
	public int DoNetRequest(){
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo == null || !networkInfo.isConnected())
		{
			Toast.makeText(context, "您的网络有问题!", Toast.LENGTH_SHORT).show();
			return REQUEST_OFFLINE;
		}
		thread = new Thread()
		{
			@Override
			public void run()
			{
				super.run();
				task.beforeRequest(context);
				task.request(context ,mHandler,messageWhat,dataTag);
				task.afterRequest(context);
				Log.i("NetTaskManager", "Thread run complete");
			}
		};
		thread.start();
		return START_REQUEST_SUCCESS;
	}
}

